package com.xjoyt.pay.master.core.order.handle.callback;

import java.util.Date;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import com.xjoyt.pay.dto.ExecuteResult;
import com.xjoyt.pay.gateway.params.CallbackParam;
import com.xjoyt.pay.master.core.order.handle.AbstractOrderCallbackHandle;
import com.xjoyt.pay.master.dto.CallbackResult;
import com.xjoyt.pay.master.dto.OrderUrlResult;
import com.xjoyt.pay.master.po.Order;
import com.xjoyt.pay.master.repository.OrderRepository;

/**
 * 处理对账
 * 
 * @author Administrator
 *
 */
@Component
public class CheckHandle extends AbstractOrderCallbackHandle {

	@Autowired
	private OrderRepository repository;

	@Autowired
	private RestTemplate restTemplate;

	@Override
	public ExecuteResult<CallbackResult> handle(CallbackParam param, Order order) throws Exception {

		CallbackResult callback = new CallbackResult();
		callback.callbackResponse = order.orderConfig.callbackResponse;
		callback.callbackResult = order.orderConfig.callbackResult;
		callback.success = true;
//		callback.merchantId = order.merchant.id;
//		callback.distributorId = order.merchant.distributor.id;
//		callback.companyId = order.merchant.distributor.company.id;

		if (StringUtils.isBlank(order.orderConfig.checkUrl)) {
			if (order.check == null) {
				order.check = false;
				repository.save(order);
			}
			AbstractOrderCallbackHandle next = getNext();
			if (next == null)
				return ExecuteResult.ok(callback);
			else
				return next.handle(param, order);
		}

		try {
			OrderUrlResult result = restTemplate.postForObject(order.orderConfig.checkUrl, order, OrderUrlResult.class);
			if (result != null && result.success) {
				order.check = true;
				order.checkDate = new Date();
				order.checkType = 0;
				order.checkMoney = result.money;
			} else {
				order.check = false;
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("调用对账错误", e);
			order.check = false;
		}
		repository.save(order);
		AbstractOrderCallbackHandle next = getNext();
		if (next == null)
			return ExecuteResult.ok(callback);
		else
			return next.handle(param, order);
	}

}
